<template>
  <div class="yearly">
    <div
      class="fold"
      v-if="foldList && foldList.length !== 0"
      @click="showFoldList"
    >
      <RightOutlined />
    </div>
    <div class="wrapper flex">
      <div class="plan-list flex" v-if="planList && planList.length !== 0">
        <div
          ref="planItemRef"
          :class="[
            'plan-item ml-30 mt-30 flex-column',
            { 'fold-item': item.fold },
          ]"
          v-for="item of planList"
          :key="item.id"
        >
          <div class="title common-class flex-column-center">
            <div class="label flex-column-center">
              <img src="../../assets/images/yearly/goal.svg" />
              <span>目标：</span>
            </div>
            <span class="title-text">{{ item.goal }}</span>
            <div class="edit-wrap">
              <a-checkbox
                v-model:checked="item.checkedFlag"
                @click="(e) => checkedGoal(e, item)"
              ></a-checkbox>
              <img
                class="ml-5"
                src="../../assets/images/edit.svg"
                @click="editGoal(item)"
              />
              <a-tooltip placement="right">
                <template #title
                  >可将已完成的或暂时停滞的计划收起到左侧</template
                >
                <img
                  src="../../assets/images/fold.svg"
                  @click="foldItem(item, index)"
                />
              </a-tooltip>
            </div>
          </div>
          <div class="todo common-class">
            <div class="label flex-column-center">
              <img src="../../assets/images/yearly/running.svg" />
              <span class="ml-5">我的计划：</span>
            </div>
            <div class="content mt-10">
              {{ item.plan }}
            </div>
          </div>
          <div class="achievement common-class">
            <div class="label flex-column-center">
              <img src="../../assets/images/yearly/achievement.svg" />
              <span class="ml-5">完成信号：</span>
            </div>
            <div class="achievement-text mt-10">{{ item.achievement }}</div>
          </div>
          <div class="progress flex p-15 pl-30 pr-30">
            <a-progress
              :percent="item.percent"
              :strokeColor="
                item.percent === 100
                  ? '#52c41a'
                  : item.percent > 50
                  ? '#1677ff'
                  : '#ffc107'
              "
            />
            <a-button-group>
              <a-button @click="increase(item)" v-if="item.percent !== 100">
                <template #icon><plus-outlined /></template>
              </a-button>
              <a-button @click="decline(item)" v-if="item.percent !== 0">
                <template #icon><minus-outlined /></template>
              </a-button>
            </a-button-group>
          </div>
        </div>
      </div>
      <div class="empty-text plan-list flex-center" v-else>
        <div class="loading-text">
          <span style="--i: 1">快</span>
          <span style="--i: 2">去</span>
          <span style="--i: 3">创</span>
          <span style="--i: 4">建</span>
          <span style="--i: 5">你</span>
          <span style="--i: 6">的</span>
          <span style="--i: 7">年</span>
          <span style="--i: 8">度</span>
          <span style="--i: 9">计</span>
          <span style="--i: 10">划</span>
          <span style="--i: 11">吧</span>
          <span style="--i: 12">——></span>
        </div>
      </div>
      <div class="yearly-plan flex-column">
        <span class="text flex-column">
          <span>年</span>
          <span>度</span>
          <span>计</span>
          <span>划</span>
        </span>
        <a-button @click="createGoal" type="primary" class="mt-30"
          >创建我的年度计划</a-button
        >
      </div>
    </div>

    <a-modal
      v-model:open="dialogConfig.show"
      :title="dialogConfig.title"
      :confirm-loading="dialogConfig.loading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form
        ref="dialogFormRef"
        :model="dialogConfig.form"
        :rules="dialogConfig.rules"
        :label-col="{ span: 3 }"
        style="margin-top: 24px"
      >
        <a-form-item label="目标" name="goal">
          <a-input
            v-model:value="dialogConfig.form.goal"
            placeholder="年度目标"
          />
        </a-form-item>
        <a-form-item label="计划" name="plan" style="margin-top: 8px">
          <a-textarea
            v-model:value="dialogConfig.form.plan"
            placeholder="为了实现该目标要做的一些行动"
            :auto-size="{ minRows: 2, maxRows: 5 }"
          />
        </a-form-item>
        <a-form-item label="表现" name="achievement" style="margin-top: 8px">
          <a-textarea
            v-model:value="dialogConfig.form.achievement"
            placeholder="目标实现后有什么表现"
            :auto-size="{ minRows: 2, maxRows: 5 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-drawer
      :width="500"
      title="已折叠计划"
      placement="left"
      :open="drawerShow"
      @close="drawerShow = false"
    >
      <div class="flex-center" style="height: 100%" v-if="drawerLoading">
        <a-spin size="large" tip="Loading..." />
      </div>
      <div class="fold-drawer-wrap flex-column" v-else>
        <div class="title-list flex">
          <div class="active-line" :style="activeLineStyle"></div>
          <div
            v-for="(item, index) of foldList"
            :key="item.id"
            :class="['title-item', { active: currentIndex === index }]"
            @click="changeIndex(item, index)"
            style="font-size: 18px; margin-left: 15px"
          >
            {{ item.goal }}
          </div>
        </div>

        <a-result
          :status="currentFoldItem?.checked === 1 ? 'success' : 'info'"
          :title="currentFoldItem?.goal"
          :sub-title="currentFoldItem?.achievement"
        >
          <template #extra>
            <div class="plan">{{ currentFoldItem?.plan }}</div>
            <a-button type="primary" class="mt-10" @click="moveBackPage"
              >移回页面</a-button
            >
            <a-button type="primary" danger class="mt-10" @click="deletePlan"
              >删除计划</a-button
            >
          </template>
        </a-result>
      </div>
    </a-drawer>
  </div>
</template>

<script setup>
import { reactive, ref, createVNode, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  RightOutlined,
  MinusOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons-vue";

import {
  getYearlyPlan,
  addYearlyPlan,
  updateYearlyPlan,
  deleteYearlyPlan,
  updateYearlyPlanPercent,
  foldYearlyPlanPercent,
} from "../../api/plan/yearly";
import { clearObject, debounce } from "../../utils/util";
import { getToday } from "../../utils/date";

const planList = ref([]);
const foldList = ref([]);
const drawerShow = ref(false);
const currentIndex = ref(0);
const currentFoldItem = ref(null);
const drawerLoading = ref(false);
const activeLineStyle = ref({
  left: "15px",
  width: "35px",
  height: "2px",
});
function changeIndex(item, index) {
  currentIndex.value = index;
  currentFoldItem.value = item;
  activeLineStyle.value.left = `${index * 50 + 15}px`;
}

function checkedGoal(e, item) {
  e.preventDefault();
  let text = item.checked
    ? "取消勾选意味着计划有变动,当前计划进度将清零!"
    : "勾选意味着目标已完成,当前进度将为调整为100%!";
  Modal.confirm({
    icon: () =>
      createVNode(
        item.checked ? ExclamationCircleOutlined : CheckCircleOutlined
      ),
    title: "目标确认",
    content: () => createVNode("div", {}, text),
    okText: "确定",
    onOk() {
      updateYearlyPlanPercent({
        percent: item.checked ? 0 : 100,
        id: item.id,
      }).then((res) => {
        if (res.code === 0) {
          !item.checked && message.success("太棒了!完成了一项年度计划!");
          getList();
        }
      });
    },
    onCancel() {
      console.log("Cancel");
    },
  });
}

function editGoal(item) {
  dialogConfig.form.goal = item.goal;
  dialogConfig.form.plan = item.plan;
  dialogConfig.form.achievement = item.achievement;
  dialogConfig.form.id = item.id;
  dialogConfig.title = `修改【${item.goal}】计划`;
  dialogConfig.show = true;
}

function foldItem(item, index) {
  item.fold = true;
  foldYearlyPlanPercent({
    fold: 1,
    id: item.id,
  }).then((res) => {
    if (res.code === 0) {
      getList();
      getFoldList();
    }
  });
}

function getFoldList() {
  return new Promise((resolve) => {
    getYearlyPlan({
      date: date.value.year,
      fold: 1,
    }).then((res) => {
      if (res.code === 0) {
        foldList.value = res.data;
      }
      resolve();
    });
  });
}

function showFoldList() {
  return new Promise((resolve) => {
    drawerShow.value = true;
    getFoldList().then(() => {
      currentFoldItem.value = foldList.value[0];
      currentIndex.value = 0;
      resolve();
    });
  });
}

function moveBackPage() {
  drawerLoading.value = true;
  foldYearlyPlanPercent({
    fold: 0,
    id: currentFoldItem.value.id,
  }).then((res) => {
    if (res.code === 0) {
      getList();
      showFoldList().then(() => {
        drawerLoading.value = false;
        if (foldList.value.length === 0) {
          drawerShow.value = false;
        }
      });
      activeLineStyle.value.left = "15px";
    }
  });
}

function deletePlan() {
  Modal.confirm({
    icon: () => createVNode(ExclamationCircleOutlined),
    title: "删除计划",
    content: () => createVNode("div", {}, "删除计划将无法再找回!"),
    okText: "确定",
    onOk() {
      drawerLoading.value = true;
      deleteYearlyPlan({
        id: currentFoldItem.value.id,
      }).then((res) => {
        if (res.code === 0) {
          showFoldList().then(() => {
            drawerLoading.value = false;
          });
          activeLineStyle.value.left = "15px";
        }
      });
    },
    onCancel() {
      console.log("Cancel");
    },
  });
}

const increase = debounce(increaseMethod, 1000, true);
function increaseMethod(item) {
  updateYearlyPlanPercent({
    percent: item.percent + 5,
    id: item.id,
  }).then((res) => {
    if (res.code === 0) {
      getList();
      message.success("百尺竿头,更进一步!");
    }
  });
}
const decline = debounce(declineMethod, 1000, true);
function declineMethod(item) {
  updateYearlyPlanPercent({
    percent: item.percent - 5,
    id: item.id,
  }).then((res) => {
    if (res.code === 0) {
      getList();
    }
  });
}

let date = ref(getToday());
function getList() {
  let params = {
    date: date.value.year,
  };
  getYearlyPlan(params).then((res) => {
    if (res.code === 0) {
      res.data.forEach((item) => {
        item.checkedFlag = item.checked === 1;
      });
      planList.value = res.data;
    }
  });
}

onMounted(() => {
  getList();
  getFoldList();
});

const dialogConfig = reactive({
  title: "",
  show: false,
  form: {},
  loading: false,
  rules: {
    goal: [
      {
        required: true,
        message: "请填写目标",
        trigger: "change",
      },
    ],
    plan: [
      {
        required: true,
        message: "请填写计划",
        trigger: "change",
      },
    ],
    achievement: [
      {
        required: true,
        message: "请填写表现",
        trigger: "change",
      },
    ],
  },
});

function createGoal() {
  clearObject(dialogConfig.form);
  dialogConfig.title = `创建我的【${date.value.year}】年度计划`;
  dialogConfig.show = true;
}
const dialogFormRef = ref(null);
function handleOk() {
  dialogFormRef.value
    .validate()
    .then(() => {
      dialogConfig.loading = true;
      let params = { ...dialogConfig.form };
      params.date = date.value.year;
      let api = params.id ? updateYearlyPlan : addYearlyPlan;
      api(params).then((res) => {
        dialogConfig.loading = false;
        if (res.code === 0) {
          dialogConfig.show = false;
          getList();
        } else {
          message.error(res.data.message);
        }
      });
    })
    .catch((error) => console.error(error));
}

function handleCancel() {}
</script>

<style scoped lang="less">
@keyframes slideOut {
  from {
    transform: translateX(0);
  }

  to {
    transform: translateX(-2400px);
  }
}

@keyframes upDown {
  0% {
    transform: translateY(0);
  }

  20% {
    transform: translateY(-24px);
  }

  40%,
  100% {
    transform: translateY(0);
  }
}

@border-color: #cfd8e3;

.yearly {
  height: 100%;
  padding: 16px;
  font-size: 16px;

  .fold {
    position: absolute;
    font-size: 24px;
    left: 16px;
    z-index: 999;
    top: 40%;
    cursor: pointer;
  }

  .wrapper {
    height: 100%;
    background-color: #ffffffad;
    border-radius: 16px;
    margin: 0 auto;
    position: relative;

    .plan-list {
      height: 100%;
      padding-bottom: 24px;
      overflow-y: auto;
      flex: 1;
      flex-wrap: wrap;

      .plan-item {
        width: calc(33.33% - 45px);
        height: calc(100% - 60px);
        background-color: #f0f4f8;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);

        &.fold-item {
          animation: slideOut 1s forwards;
        }

        .common-class {
          padding: 8px;
          border-bottom: 1px solid @border-color;

          .label {
            font-size: 12px;

            img {
              width: 24px;
              height: 24px;
            }
          }
        }

        .title {
          position: relative;

          .edit-wrap {
            position: absolute;
            right: 16px;

            img {
              width: 24px;
              height: 24px;
              cursor: pointer;

              &:hover {
                opacity: 0.7;
              }
            }
          }
        }

        .todo {
          flex: 1;
          overflow-y: auto;

          .content {
            text-indent: 28px;
            letter-spacing: 1px;
            line-height: 24px;
          }
        }

        .achievement {
          height: 88px;
          overflow-y: auto;

          &-text {
            text-indent: 28px;
            letter-spacing: 0.5px;
            font-size: 14px;
          }
        }

        .progress {
          align-items: baseline;
        }
      }
    }

    .empty-text {
      background-image: linear-gradient(to right, #c2e9e8 0%, #fde2eb 100%);
      border-radius: 36px;

      .loading-text {
        font-size: 50px;

        span {
          display: inline-block;
          animation: upDown 1.5s ease-in-out infinite;
          animation-delay: calc(0.1s * var(--i));
        }
      }
    }

    .yearly-plan {
      width: 300px;
      padding: 30px;

      .text {
        font-size: 32px;
        align-items: flex-end;
      }

      :deep(.ant-btn) {
        align-self: center;
      }
    }
  }
}

.fold-drawer-wrap {
  .title-list {
    border-bottom: 1px solid rgba(5, 5, 5, 0.06);
    padding-bottom: 8px;
    cursor: pointer;
    position: relative;

    .active-line {
      position: absolute;
      bottom: 0;
      background-color: #1677ff;
      transition: left 0.3s ease-in-out;
    }

    .title-item {
      transition: color 0.5s;

      &.active {
        color: #1677ff;
      }
    }
  }

  :deep(.ant-result-subtitle) {
    text-align: left;
    padding: 0 10%;
  }

  .plan {
    text-align: left;
    text-indent: 28px;
    letter-spacing: 1px;
    line-height: 20px;
  }
}
</style>
